<template>
  <div class="ai-test-page">
    <div class="container mx-auto px-4 py-8">
      <div class="max-w-4xl mx-auto">
        <div class="text-center mb-8">
          <h1 class="text-3xl font-bold text-gray-900 mb-4">
            AI功能测试页面
          </h1>
          <p class="text-gray-600">
            测试AI智能法律服务的各项功能
          </p>
        </div>

        <!-- AI状态检查 -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-8">
          <h2 class="text-xl font-semibold mb-4">
            AI服务状态
          </h2>
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-3">
              <div 
                class="w-3 h-3 rounded-full"
                :class="{
                  'bg-green-500': aiStore.aiHealthStatus?.success,
                  'bg-red-500': aiStore.aiHealthStatus?.success === false,
                  'bg-yellow-500': !aiStore.aiHealthStatus
                }"
              />
              <span class="text-sm text-gray-600">
                {{ aiStore.aiHealthStatus?.success ? '服务正常' : 
                  aiStore.aiHealthStatus?.success === false ? '服务异常' : '检查中...' }}
              </span>
            </div>
            <button 
              :disabled="isChecking"
              class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:opacity-50"
              @click="checkAIHealth"
            >
              {{ isChecking ? '检查中...' : '检查状态' }}
            </button>
          </div>
          
          <div
            v-if="aiStore.aiHealthStatus"
            class="mt-4 text-sm text-gray-500"
          >
            <div>模型: {{ aiStore.aiHealthStatus.model || 'N/A' }}</div>
            <div>响应时间: {{ aiStore.aiHealthStatus.responseTime ? Math.round(aiStore.aiHealthStatus.responseTime * 1000) + 'ms' : 'N/A' }}</div>
          </div>
        </div>

        <!-- 功能测试区域 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- 条文解读测试 -->
          <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 class="text-lg font-semibold mb-4 flex items-center gap-2">
              <span>📖</span>
              条文解读测试
            </h3>
            <textarea
              v-model="explainText"
              placeholder="输入需要解读的法律条文..."
              class="w-full p-3 border border-gray-300 rounded-md mb-4 h-24 resize-none"
            />
            <button
              :disabled="!explainText.trim() || aiStore.isLoading"
              class="w-full px-4 py-2 bg-purple-500 text-white rounded-md hover:bg-purple-600 disabled:opacity-50"
              @click="testExplain"
            >
              {{ aiStore.isLoading ? '解读中...' : '开始解读' }}
            </button>
            <div
              v-if="explainResult"
              class="mt-4 p-3 bg-gray-50 rounded-md"
            >
              <div class="text-sm text-gray-600 mb-2">
                AI解读结果：
              </div>
              <div class="text-sm">
                {{ explainResult }}
              </div>
            </div>
          </div>

          <!-- 法律问答测试 -->
          <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 class="text-lg font-semibold mb-4 flex items-center gap-2">
              <span>❓</span>
              法律问答测试
            </h3>
            <textarea
              v-model="questionText"
              placeholder="输入您的法律问题..."
              class="w-full p-3 border border-gray-300 rounded-md mb-4 h-24 resize-none"
            />
            <button
              :disabled="!questionText.trim() || aiStore.isLoading"
              class="w-full px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 disabled:opacity-50"
              @click="testQuestion"
            >
              {{ aiStore.isLoading ? '回答中...' : '提问' }}
            </button>
            <div
              v-if="questionResult"
              class="mt-4 p-3 bg-gray-50 rounded-md"
            >
              <div class="text-sm text-gray-600 mb-2">
                AI回答：
              </div>
              <div class="text-sm">
                {{ questionResult }}
              </div>
            </div>
          </div>

          <!-- 搜索建议测试 -->
          <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 class="text-lg font-semibold mb-4 flex items-center gap-2">
              <span>💡</span>
              搜索建议测试
            </h3>
            <input
              v-model="suggestionQuery"
              placeholder="输入搜索关键词..."
              class="w-full p-3 border border-gray-300 rounded-md mb-4"
            >
            <button
              :disabled="!suggestionQuery.trim() || aiStore.isLoading"
              class="w-full px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:opacity-50"
              @click="testSuggestions"
            >
              {{ aiStore.isLoading ? '生成中...' : '获取建议' }}
            </button>
            <div
              v-if="suggestionResult"
              class="mt-4"
            >
              <div class="text-sm text-gray-600 mb-2">
                搜索建议：
              </div>
              <div class="flex flex-wrap gap-2">
                <span
                  v-for="suggestion in suggestionResult"
                  :key="suggestion"
                  class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full"
                >
                  {{ suggestion }}
                </span>
              </div>
            </div>
          </div>

          <!-- 场景分析测试 -->
          <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 class="text-lg font-semibold mb-4 flex items-center gap-2">
              <span>🔍</span>
              场景分析测试
            </h3>
            <textarea
              v-model="scenarioText"
              placeholder="描述具体的法律场景..."
              class="w-full p-3 border border-gray-300 rounded-md mb-4 h-24 resize-none"
            />
            <button
              :disabled="!scenarioText.trim() || aiStore.isLoading"
              class="w-full px-4 py-2 bg-orange-500 text-white rounded-md hover:bg-orange-600 disabled:opacity-50"
              @click="testScenario"
            >
              {{ aiStore.isLoading ? '分析中...' : '开始分析' }}
            </button>
            <div
              v-if="scenarioResult"
              class="mt-4 p-3 bg-gray-50 rounded-md"
            >
              <div class="text-sm text-gray-600 mb-2">
                分析结果：
              </div>
              <div class="text-sm space-y-2">
                <div v-if="scenarioResult.key_points">
                  <strong>关键要点：</strong>
                  <ul class="list-disc list-inside ml-2">
                    <li
                      v-for="point in scenarioResult.key_points"
                      :key="point"
                    >
                      {{ point }}
                    </li>
                  </ul>
                </div>
                <div v-if="scenarioResult.preliminary_advice">
                  <strong>初步建议：</strong>
                  <p>{{ scenarioResult.preliminary_advice }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 对话历史 -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mt-8">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold">
              对话历史 ({{ aiStore.conversations.length }})
            </h3>
            <button
              :disabled="aiStore.conversations.length === 0"
              class="px-3 py-1 text-sm bg-red-500 text-white rounded-md hover:bg-red-600 disabled:opacity-50"
              @click="clearHistory"
            >
              清空历史
            </button>
          </div>
          
          <div
            v-if="aiStore.conversations.length === 0"
            class="text-center text-gray-500 py-8"
          >
            暂无对话历史
          </div>
          
          <div
            v-else
            class="space-y-4 max-h-96 overflow-y-auto"
          >
            <div
              v-for="conversation in aiStore.conversations.slice(-10)"
              :key="conversation.id"
              class="border-l-4 border-blue-200 pl-4 py-2"
            >
              <div class="text-sm text-gray-600 mb-1">
                {{ formatTime(conversation.timestamp) }} - {{ getTypeLabel(conversation.type) }}
              </div>
              <div class="text-sm font-medium text-gray-800 mb-1">
                输入: {{ conversation.input.substring(0, 100) }}{{ conversation.input.length > 100 ? '...' : '' }}
              </div>
              <div class="text-sm text-gray-600">
                输出: {{ conversation.output.substring(0, 100) }}{{ conversation.output.length > 100 ? '...' : '' }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useAIStore } from '@/stores/ai'

const aiStore = useAIStore()

// 测试数据
const explainText = ref('第一千零四十六条 结婚应当男女双方完全自愿，禁止任何一方对另一方加以强迫，禁止任何组织或者个人加以干涉。')
const questionText = ref('我在网上买的衣服有质量问题，商家不给退，我该怎么办？')
const suggestionQuery = ref('离婚')
const scenarioText = ref('我租的房子还没到期，房东突然要把房子卖了，让我一个月内搬走，这合法吗？')

// 测试结果
const explainResult = ref('')
const questionResult = ref('')
const suggestionResult = ref([])
const scenarioResult = ref(null)

// 状态
const isChecking = ref(false)

// 方法
const checkAIHealth = async () => {
  isChecking.value = true
  try {
    await aiStore.checkAIHealth()
  } catch (error) {
    console.error('健康检查失败:', error)
  } finally {
    isChecking.value = false
  }
}

const testExplain = async () => {
  try {
    const result = await aiStore.explainArticle(explainText.value)
    explainResult.value = result.explanation
  } catch (error) {
    explainResult.value = `错误: ${error.message}`
  }
}

const testQuestion = async () => {
  try {
    const result = await aiStore.answerQuestion(questionText.value)
    questionResult.value = result.answer
  } catch (error) {
    questionResult.value = `错误: ${error.message}`
  }
}

const testSuggestions = async () => {
  try {
    const result = await aiStore.getSearchSuggestions(suggestionQuery.value)
    suggestionResult.value = result.suggestions
  } catch (error) {
    suggestionResult.value = [`错误: ${error.message}`]
  }
}

const testScenario = async () => {
  try {
    const result = await aiStore.analyzeScenario(scenarioText.value)
    scenarioResult.value = result.analysis
  } catch (error) {
    scenarioResult.value = { preliminary_advice: `错误: ${error.message}` }
  }
}

const clearHistory = () => {
  if (confirm('确定要清空所有对话历史吗？')) {
    aiStore.clearConversations()
  }
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

const getTypeLabel = (type) => {
  const labels = {
    explain: '条文解读',
    question: '法律问答',
    suggestions: '搜索建议',
    scenario: '场景分析'
  }
  return labels[type] || type
}

onMounted(() => {
  // 初始化AI服务
  aiStore.initialize()
})
</script>

<style scoped>
.ai-test-page {
  min-height: 100vh;
  background: #f8fafc;
}
</style>
